
#include "gamewindow.h"
#include <QKeyEvent>
#include <QRandomGenerator>
#include <QGraphicsPixmapItem>
#include <QDebug>

// ================= 玩家类实现 =================
Player::Player(QGraphicsItem *parent) : QGraphicsPixmapItem(parent) {
    // 加载玩家图片（确保路径正确）
    setPixmap(QPixmap(":/images/player.png").scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation));
    isJumping = false;
    velocity = 0;
    jumpCount = 0;
    maxJumpCount = 2;
}

void Player::jump() {
    if (jumpCount < maxJumpCount) {
        velocity = -15;
        isJumping = true;
        jumpCount++;
    }
}

void Player::updatePosition() {
    if (isJumping) {
        setPos(x(), y() + velocity);
        velocity += 1.0;
        if (y() >= 250) { // 地面高度
            setPos(x(), 250);
            isJumping = false;
            velocity = 0;
            jumpCount = 0;
        }
    }
}

// ================= 游戏窗口类实现 =================
GameWindow::GameWindow(QWidget *parent) : QMainWindow(parent) {
    // 初始化场景和视图
    scene = new QGraphicsScene(this);
    view = new QGraphicsView(scene);
    setCentralWidget(view);

    // 窗口设置
    setFixedSize(800, 400);
    view->setFixedSize(800, 400);
    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 加载背景（关键检查）
    QPixmap bgPixmap(":/images/background.jpg");
    if(bgPixmap.isNull()) {
        qDebug() << "背景加载失败！检查路径和资源文件";
    } else {
        QGraphicsPixmapItem *bg = new QGraphicsPixmapItem(bgPixmap.scaled(800, 400));
        bg->setZValue(-1);
        scene->addItem(bg);
    }

    // 初始化玩家
    player = new Player();
    player->setPos(100, 250);
    scene->addItem(player);

    // 游戏系统
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &GameWindow::updateGame);
    timer->start(30);

    resetGame();
}

void GameWindow::keyPressEvent(QKeyEvent *event) {
    if (isGameOver && event->key() == Qt::Key_R) {
        resetGame();
    } else if (!isGameOver &&
               (event->key() == Qt::Key_Space ||
                event->key() == Qt::Key_Up)) {
        player->jump();
    }
}

void GameWindow::updateGame() {
    if (!isGameOver) {
        player->updatePosition();
        spawnObstacle();
        checkCollision();

        // 简单得分：每秒+10分
        score++;
        setWindowTitle(QString("跑酷游戏 | 得分: %1 | 剩余跳跃: %2")
                           .arg(score/10).arg(player->maxJumpCount - player->jumpCount));
    }
}

void GameWindow::spawnObstacle() {
    // 障碍物生成（3%概率）
    if (QRandomGenerator::global()->bounded(100) < 3) {
        QPixmap obsPixmap(":/images/obstacle.png");
        if(obsPixmap.isNull()) {
            qDebug() << "障碍物图片加载失败";
            return;
        }
        QGraphicsPixmapItem *obstacle = new QGraphicsPixmapItem(obsPixmap.scaled(40, 40));
        obstacle->setPos(800, 260);
        scene->addItem(obstacle);
    }

    // 移动障碍物
    foreach (QGraphicsItem *item, scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item)) {
            item->setPos(item->x() - 5, item->y());
            if (item->x() < -50) {
                scene->removeItem(item);
                delete item;
            }
        }
    }
}

void GameWindow::checkCollision() {
    foreach (QGraphicsItem *item, scene->collidingItems(player)) {
        if (dynamic_cast<QGraphicsPixmapItem*>(item)) {
            gameOver();
            return;
        }
    }
}

void GameWindow::gameOver() {
    isGameOver = true;
    timer->stop();
    QGraphicsTextItem *text = scene->addText("游戏结束！按R重新开始", QFont("Arial", 24));
    text->setDefaultTextColor(Qt::white);
    text->setPos(200, 150);
}

void GameWindow::resetGame() {
    // 清理障碍物
    foreach (QGraphicsItem *item, scene->items()) {
        if (item != player && dynamic_cast<QGraphicsPixmapItem*>(item)) {
            scene->removeItem(item);
            delete item;
        }
    }

    // 重置状态
    player->setPos(100, 250);
    player->isJumping = false;
    player->jumpCount = 0;
    score = 0;
    isGameOver = false;

    if (!timer->isActive()) timer->start();
}
